package com.ruoyi.system.service.impl;

import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.BuzTaskAwardsTj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.ruoyi.system.mapper.BuzTaskUserMapper;
import com.ruoyi.system.domain.BuzTaskUser;
import com.ruoyi.system.service.IBuzTaskUserService;

/**
 * 用户答题情况Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-08-31
 */
@Service
public class BuzTaskUserServiceImpl implements IBuzTaskUserService 
{
    @Autowired
    private BuzTaskUserMapper buzTaskUserMapper;
    
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 查询用户答题情况
     * 
     * @param id 用户答题情况主键
     * @return 用户答题情况
     */
    @Override
    public BuzTaskUser selectBuzTaskUserById(String id)
    {
        return buzTaskUserMapper.selectBuzTaskUserById(id);
    }

    /**
     * 查询用户答题情况列表
     * 
     * @param buzTaskUser 用户答题情况
     * @return 用户答题情况
     */
    @Override
    public List<BuzTaskUser> selectBuzTaskUserList(BuzTaskUser buzTaskUser)
    {
        return buzTaskUserMapper.selectBuzTaskUserList(buzTaskUser);
    }
    
    @Override
    public List<Map> getTodayAwards(BuzTaskUser buzTaskUser)
    {
        return buzTaskUserMapper.getTodayAwards(buzTaskUser);
    }

    /**
     * 新增用户答题情况
     * 
     * @param buzTaskUser 用户答题情况
     * @return 结果
     */
    @Override
    public int insertBuzTaskUser(BuzTaskUser buzTaskUser)
    {
        return buzTaskUserMapper.insertBuzTaskUser(buzTaskUser);
    }

    /**
     * 修改用户答题情况
     * 
     * @param buzTaskUser 用户答题情况
     * @return 结果
     */
    @Override
    public int updateBuzTaskUser(BuzTaskUser buzTaskUser)
    {
        return buzTaskUserMapper.updateBuzTaskUser(buzTaskUser);
    }
    
    @Override
    public int updateReceiveAwardsTime(BuzTaskUser buzTaskUser)
    {
        return buzTaskUserMapper.updateReceiveAwardsTime(buzTaskUser);
    }
    
    /**
     * 修改用户答题情况
     * 
     * @param buzTaskUser 用户答题情况
     * @return 结果
     */
    @Override
    public int updateSaveQuestion(BuzTaskUser buzTaskUser)
    {
        return buzTaskUserMapper.updateSaveQuestion(buzTaskUser);
    }
    
    /**
     * 修改用户答题情况
     * 
     * @param buzTaskUser 用户答题情况
     * @return 结果
     */
    @Override
    public int nullReceiveAwardsTime(BuzTaskUser buzTaskUser)
    {
        return buzTaskUserMapper.nullReceiveAwardsTime(buzTaskUser);
    }

    /**
     * 批量删除用户答题情况
     * 
     * @param ids 需要删除的用户答题情况主键
     * @return 结果
     */
    @Override
    public int deleteBuzTaskUserByIds(String[] ids)
    {
        return buzTaskUserMapper.deleteBuzTaskUserByIds(ids);
    }

    /**
     * 删除用户答题情况信息
     * 
     * @param id 用户答题情况主键
     * @return 结果
     */
    @Override
    public int deleteBuzTaskUserById(String id)
    {
        return buzTaskUserMapper.deleteBuzTaskUserById(id);
    }

    public int getCountByTaskId(String taskId){
        return buzTaskUserMapper.getCountByTaskId(taskId);
    }
    public int getCountByTaskIdAndUserId(String taskId, String userId){
        BuzTaskUser buzTaskUser = new BuzTaskUser();
        buzTaskUser.setTaskId(taskId);
        buzTaskUser.setMemberId(userId);
        return buzTaskUserMapper.getCountByTaskIdAndUserId(buzTaskUser);
    }

    public int getCountByTaskIdAndUserIdPerDay(String taskId, String userId){
        BuzTaskUser buzTaskUser = new BuzTaskUser();
        buzTaskUser.setTaskId(taskId);
        buzTaskUser.setMemberId(userId);
        return buzTaskUserMapper.getCountByTaskIdAndUserIdPerDay(buzTaskUser);
    }
    
    
    @Override
    public int getAwardCountByLongitudePerDay(String id)
    {
        return buzTaskUserMapper.getAwardCountByLongitudePerDay(id);
    }
    
    @Override
    public int getCountByTaskIdByMemberIdCurrDay(BuzTaskUser buzTaskUser)
    {
        return buzTaskUserMapper.getCountByTaskIdByMemberIdCurrDay(buzTaskUser);
    }
    
    @Override
    public int getCountByTaskIdByLongitude(BuzTaskUser buzTaskUser)
    {
        return buzTaskUserMapper.getCountByTaskIdByLongitude(buzTaskUser);
    }

    public int getAwardCountByTaskId(String taskId){
        return buzTaskUserMapper.getAwardCountByTaskId(taskId);
    }
    public int getAwardCountByTaskIdPerDay(String taskId){
        return buzTaskUserMapper.getAwardCountByTaskIdPerDay(taskId);
    }
    public int getAwardCountByTaskIdAndMemberId(String taskId, String userId){
        BuzTaskUser buzTaskUser = new BuzTaskUser();
        buzTaskUser.setTaskId(taskId);
        buzTaskUser.setMemberId(userId);
        int count=buzTaskUserMapper.getAwardCountByTaskIdAndMemberId(buzTaskUser);
        return count;
    }
    public int getAwardCountByTaskIdAndMemberIdPerDay(String taskId, String userId){
        BuzTaskUser buzTaskUser = new BuzTaskUser();
        buzTaskUser.setTaskId(taskId);
        buzTaskUser.setMemberId(userId);
        return buzTaskUserMapper.getAwardCountByTaskIdAndMemberIdPerDay(buzTaskUser);
    }
    public Map<String, Object> getTaskAwardsTjResult(String taskId){
        HashMap resultMap = new HashMap<>(16);
        List<BuzTaskAwardsTj> tjList = buzTaskUserMapper.selectTaskAwardsTjResultList(taskId);
        resultMap.put("tjList", tjList);
        resultMap.put("count", buzTaskUserMapper.getItemCount(taskId));
        resultMap.put("levelCount", buzTaskUserMapper.getAwardsLevelCount(taskId));

        return resultMap;
    }
    @Override
	public Map<String, Object> getTaskAwardsTjResult(String taskId, Integer page, Integer pageSize,Boolean isCount) {
        HashMap resultMap = new HashMap<>(16);
        // 分页查询sql优化过，可以短时间查询出数据，但是代价是统计需要分开计算
        List<BuzTaskAwardsTj> tjList = buzTaskUserMapper.selectTaskAwardsTjResultList2(taskId,(page-1)*pageSize,pageSize);
        
        resultMap.put("tjList", tjList);
        // 如果不统计，则不需要查询结果
        if(isCount) {
            Integer total =  buzTaskUserMapper.selectTaskAwardsTjResultListCount(taskId);
            resultMap.put("total", total);
        }
        //resultMap.put("count", buzTaskUserMapper.getItemCount(taskId));
        //resultMap.put("levelCount", buzTaskUserMapper.getAwardsLevelCount(taskId));
        
        //resultMap.put("count", buzTaskUserMapper.getItemCount(taskId));
        //resultMap.put("levelCount", buzTaskUserMapper.getAwardsLevelCount(taskId));

        return resultMap;
	}
    
    public Map<String, Object> getTaskExamTjResult(String taskId){
        HashMap resultMap = new HashMap<>(16);
        
        List<BuzTaskAwardsTj> tjList = buzTaskUserMapper.selectTaskAwardsTjResultList(taskId);
        resultMap.put("tjList", tjList);
        resultMap.put("count", buzTaskUserMapper.getItemCount(taskId));
        resultMap.put("levelCount", buzTaskUserMapper.getAwardsLevelCount(taskId));

        return resultMap;
    }

    @Override
    public List<Map<String, Object>> getTaskAwardsInfoByTask(String taskId, String userId) {
        BuzTaskUser buzTaskUser = new BuzTaskUser();
        buzTaskUser.setTaskId(taskId);
        buzTaskUser.setMemberId(userId);
        return buzTaskUserMapper.getTaskAwardsInfoByTask(buzTaskUser);
    }
    
    @Override
    public List<Map<String, Object>> getSubmitListByTask(String taskId, String userId) {
        BuzTaskUser buzTaskUser = new BuzTaskUser();
        buzTaskUser.setTaskId(taskId);
        buzTaskUser.setMemberId(userId);
        return buzTaskUserMapper.getSubmitListByTask(buzTaskUser);
    }
    
  //发送奖励
    public int sendWards(BuzTaskUser buzTaskUser,String openId) {
    	String responseStr=sendRedPackUrl(buzTaskUser.getId(),openId,buzTaskUser.getAwardsMoney().toString());
    	
    	buzTaskUser.setReceiveAwardsStatus(responseStr);
    	buzTaskUserMapper.updateReceiveAwardsStatus(buzTaskUser);
    	return 1;
    }
    
    /**
     * 第三方红包直发接口
     */
    private String sendRedPackUrl(String orderId, String openId, String money){
    	String responseStr ="";
    	try {
	    	// 设置时间服务器的URL
	        URL timeUrl = new URL("http://www.baidu.com");
	        URLConnection conn = timeUrl.openConnection();
	        conn.connect();
	        
	        // 获取时间服务器返回的时间
	        long serverTime = conn.getDate();
	        Date date = new Date(serverTime);
	        long reqtick= date.getTime();
	    	
	        String uid = "10810602";
	        String type = "1";
	        //long reqtick= new Date().getTime();
	        reqtick=reqtick/1000;
	
	        String apikey = "TSGCY6rzFW6TzhAd";
	        System.out.println("----------money："+money);
	        Float fen=new Float(money)*100;
	        System.out.println("----------fen："+fen.intValue());
	        System.out.println("----------before md5："+uid+type+orderId+fen.intValue()+reqtick+openId+apikey);
	
	        //sign = md5(uid+type+orderid+money+reqtick+openId+apikey)
	        String sign = Md5Utils.hash(uid+type+orderId+fen.intValue()+reqtick+openId+apikey).toLowerCase();
	        System.out.println("----------after md5："+sign);
	        String url = "https://www.yaoyaola.net/exapi/SendRedPackToOpenid?uid="+uid+"&type="+type+"&orderid="+orderId+"&money="+fen.intValue()+"&reqtick="+reqtick+"&openid="+openId+"&sign="+sign+"&title=中医药有奖知识竞赛&wishing=中医药有奖知识竞赛&sendname=中医药有奖知识竞赛";
	        System.out.println("url="+url);
	        responseStr = restTemplate.getForObject(url, String.class);
	        System.out.println("--------------------------红包接口返回内容-----------"+responseStr);
	        /*
	        JSONObject jsonObject = JSONObject.parseObject(responseStr);
	        if (jsonObject != null && jsonObject.containsKey("ticket")) {
	            String ticket = jsonObject.getString("ticket");
	        }
	        */
        
    	}catch(Exception e) {
    		e.printStackTrace();
    		
    	}
    	return responseStr;
    }

	@Override
	public List<BuzTaskAwardsTj> getAllTaskAwardsResult(String taksId) {
		List<BuzTaskAwardsTj> result =  buzTaskUserMapper.selectAllTaskAwardsResultList(taksId);
		return result;
	}

	@Override
	public Map<String, Object> getStatisticsByTaskId(String taskId) {
		
		Map<String,Object> result = new HashMap<>();
		List<JSONObject> countResult = new CopyOnWriteArrayList<>();
		/**多线程查询并合并结果 5个查询使用5个线程处理*/
			
		CountDownLatch countDownLatch = new CountDownLatch(5);
		ExecutorService executor = Executors.newFixedThreadPool(5);
		// 起5查询线程同时查询
		Runnable run1 = new Runnable() {
			
			@Override
			public void run() {
				Integer res1 =  buzTaskUserMapper.getJoinPerson(taskId);
				JSONObject j1 = new JSONObject();
				j1.put("item", "参与人数");
				j1.put("num", res1);
				j1.put("order", 1);
				countResult.add(j1);
				countDownLatch.countDown();
			}
		};
		executor.execute(run1);
		Runnable run2 = new Runnable() {
			
			@Override
			public void run() {
				Integer res2 =  buzTaskUserMapper.getJoinPersonTime(taskId);
				JSONObject j2 = new JSONObject();
				j2.put("item", "参与人次");
				j2.put("num", res2);
				j2.put("order", 2);
				countResult.add(j2);
				countDownLatch.countDown();
			}
		};
		executor.execute(run2);
		Runnable run3 = new Runnable() {
			
			@Override
			public void run() {
				Integer res3 =  buzTaskUserMapper.getAwardTotal(taskId);
				JSONObject j3 = new JSONObject();
				j3.put("item", "抽奖总数");
				j3.put("num", res3);
				j3.put("order", 3);
				countResult.add(j3);
				countDownLatch.countDown();
			}
		};
		executor.execute(run3);
		Runnable run4 = new Runnable() {
			
			@Override
			public void run() {
				Integer res4 =  buzTaskUserMapper.getMoneyTotal(taskId);
				JSONObject j4 = new JSONObject();
				j4.put("item", "累计中奖金额");
				j4.put("num", res4);
				j4.put("order", 4);
				countResult.add(j4);
				countDownLatch.countDown();
			}
		};
		executor.execute(run4);
		Runnable run5 = new Runnable() {
			
			@Override
			public void run() {
				Integer res5 =  buzTaskUserMapper.receiveMoneyTotal(taskId);
				JSONObject j5 = new JSONObject();
				j5.put("item", "累计领奖金额");
				j5.put("num", res5);
				j5.put("order", 5);
				countResult.add(j5);
				countDownLatch.countDown();
			}
		};
		executor.execute(run5);
		
		try {
			countDownLatch.await();
			executor.shutdown();
			List<JSONObject> finallcountResult = countResult.stream()
			.sorted((s1,s2)->s1.getInteger("order").compareTo(s2.getInteger("order")))
			.collect(Collectors.toList());
			result.put("count",finallcountResult);
			return result;
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Map<String, Object> getStatisticsAwardsByTaskId(String taskId) {
		Map<String,Object> result = new HashMap<>();
		List<Map> res= buzTaskUserMapper.getStatisticsAwardsByTaskId(taskId);
		result.put("levelCount", res);
		return result;
	}

	

}
